package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.GoodsPromotionDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 商品活动促销业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-05-15 12:54:16
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class GoodsPromotionService{

  private final GoodsPromotionDao goodsPromotionDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public GoodsPromotionService(final GoodsPromotionDao goodsPromotionDao,final ThreadPoolTaskExecutor taskExecutor){
    this.goodsPromotionDao = goodsPromotionDao;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_title = "title";
      final String p_introduce = "introduce";
      final String p_score = "score";//商品id、商品的活动价格、不同等级对应的积分数
      final String p_start_date = "start_date";
      final String p_end_date = "end_date";
      final String validate = ToolClient.validateField(formData,p_title,p_introduce,p_score,p_start_date,p_end_date);
      if(validate != null) return validate;
      final String len_title = formData.getString(p_title);
      if(len_title != null && len_title.length() > 128){
        return ToolClient.createJsonFail("活动促销名称字数太多");
      }
      final String len_introduce = formData.getString(p_introduce);
      if(len_introduce != null && len_introduce.length() > 921600000){
        return ToolClient.createJsonFail("活动介绍字数太多");
      }
      final String len_start_date = formData.getString(p_start_date);
      if(len_start_date != null && len_start_date.length() > 10){
        return ToolClient.createJsonFail("开始日期字数太多");
      }
      final String len_end_date = formData.getString(p_end_date);
      if(len_end_date != null && len_end_date.length() > 10){
        return ToolClient.createJsonFail("结束日期字数太多");
      }
      final Integer v_start_date = formData.getInteger(p_start_date);
      if(v_start_date == null){
        return ToolClient.createJsonFail("开始日期不是有效的数字");
      }else{
        formData.put(p_start_date,v_start_date);
      }
      final Integer v_end_date = formData.getInteger(p_end_date);
      if(v_end_date == null){
        return ToolClient.createJsonFail("结束日期不是有效的数字");
      }else{
        formData.put(p_end_date,v_end_date);
      }
      final long kid = new IdBuilder().getId121L();
      final String len_score = formData.getString(p_score);
      final ArrayList<HashMap<String,Object>> list = new ArrayList<>(5);
      handlerLevelScore(list,kid,len_score);
      formData.put("kid",kid);
      return ToolClient.executeRows(goodsPromotionDao.add(formData,list));
    },taskExecutor).join();
  }

  private void handlerValues(final ArrayList<HashMap<String,Object>> list,final HashMap<String,String> maps,final int level_value,final String p_level_value){
    final HashMap<String,Object> map = new HashMap<>(2);
    map.put("level_value",level_value);
    map.put("score",new BigDecimal(maps.get(p_level_value)));
    list.add(map);
  }

  public String edit(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_kid = "kid";
      final String p_title = "title";
      final String p_introduce = "introduce";
      final String p_score = "score";
      final String p_start_date = "start_date";
      final String p_end_date = "end_date";
      final String validate = ToolClient.validateField(formData,p_kid,p_title,p_introduce,p_start_date,p_end_date);
      if(validate != null) return validate;
      final String len_title = formData.getString(p_title);
      if(len_title != null && len_title.length() > 128){
        return ToolClient.createJsonFail("活动促销名称字数太多");
      }
      final String len_introduce = formData.getString(p_introduce);
      if(len_introduce != null && len_introduce.length() > 921600000){
        return ToolClient.createJsonFail("活动介绍字数太多");
      }
      final String len_start_date = formData.getString(p_start_date);
      if(len_start_date != null && len_start_date.length() > 10){
        return ToolClient.createJsonFail("开始日期字数太多");
      }
      final String len_end_date = formData.getString(p_end_date);
      if(len_end_date != null && len_end_date.length() > 10){
        return ToolClient.createJsonFail("结束日期字数太多");
      }
      if(len_start_date != null){
        final Integer v_start_date = formData.getInteger(p_start_date);
        if(v_start_date == null){
          return ToolClient.createJsonFail("开始日期不是有效的数字");
        }else{
          formData.put(p_start_date,v_start_date);
        }
      }
      if(len_end_date != null){
        final Integer v_end_date = formData.getInteger(p_end_date);
        if(v_end_date == null){
          return ToolClient.createJsonFail("结束日期不是有效的数字");
        }else{
          formData.put(p_end_date,v_end_date);
        }
      }
      final long kid = formData.getLong(p_kid);
      final Long v = goodsPromotionDao.queryExistById(kid);
      if(v == null){
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final String len_score = formData.getString(p_score);
      formData.put(p_kid,kid);
      if(len_score != null){
        final ArrayList<HashMap<String,Object>> list = new ArrayList<>(5);
        handlerLevelScore(list,kid,len_score);
        final String delIds = formData.getString("delIds");
        if(delIds != null){
          final long[] array = ToolString.keysToArarry(delIds);
          final HashMap<String,Object> params = new HashMap<>(2);
          params.put("promotion_id",kid);
          params.put("array",array);
          return ToolClient.executeRows(goodsPromotionDao.edit(formData,list,params));
        }else{
          return ToolClient.executeRows(goodsPromotionDao.edit(formData,list));
        }
      }else{
        formData.remove(p_score);
      }
      return ToolClient.executeRows(goodsPromotionDao.edit(formData));
    },taskExecutor).join();
  }

  private void handlerLevelScore(final ArrayList<HashMap<String,Object>> list,final long kid,final String len_score){
    final ArrayList<HashMap<String,String>> listHashMap = ToolString.parseJsonArray(len_score);
    for(int x = listHashMap.size() - 1; x >= 0; x--){
      final HashMap<String,String> map = listHashMap.get(x);
      final ArrayList<HashMap<String,String>> levelScore = ToolString.parseJsonArray(map.get("level_score"));
      for(int n = levelScore.size() - 1; n >= 0; n--){
        final HashMap<String,String> hashMap = levelScore.get(n);
        final HashMap<String,Object> values = new HashMap<>(5);
        values.put("promotion_id",kid);
        values.put("goods_id",Long.parseLong(map.get("goods_id")));
        values.put("price",new BigDecimal(map.get("price")));
        values.put("level_value",Integer.valueOf(hashMap.get("level_value")));
        values.put("score",new BigDecimal(hashMap.getOrDefault("score","0")));
        list.add(values);
      }
    }
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = new HashMap<>(2);
      map.put("list",getPromotionGoodsInfo(kid));
      map.put("info",goodsPromotionDao.queryById(kid));
      return ToolClient.queryJson(map);
    },taskExecutor).join();
  }

  public String queryInfo(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(getPromotionGoodsInfo(kid));
    },taskExecutor).join();
  }

  public List<HashMap<String,Object>> getPromotionGoodsInfo(final long kid){
    return goodsPromotionDao.getPromotionGoodsInfo(kid);
  }

  public String queryGoods(){
    return CompletableFuture.supplyAsync(()-> ToolClient.queryJson(goodsPromotionDao.queryGoods()),taskExecutor).join();
  }

  //编辑时的文件删除可参考此方法
  public String delById(final Long kid){
    //若用到ThreadLocal的数据可在此组装
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.executeRows(goodsPromotionDao.delById(kid),"操作成功","删除失败,刷新重试");
    },taskExecutor).join();
  }

  public String delByKeys(final String ids){
    return CompletableFuture.supplyAsync(()->{
      if(ids == null || ids.length() <= 0){
        return ToolClient.jsonValidateField();
      }
      final long[] list = ToolString.keysToArarry(ids);
      if(list == null){
        return ToolClient.createJsonFail("请选择要删除的数据");
      }
      return ToolClient.executeRows(goodsPromotionDao.delByKeys(list),"操作成功","数据不存在,刷新重试");
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> goodsPromotionDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> goodsPromotionDao.getListTotal(formData),taskExecutor);
        //CompletableFuture.allOf(listData,listTotal).join();//若出错取消注释即可
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}